package cn.xval.ft.app.gen.service.impl;

import cn.xval.fc.base.exception.Asserts;
import cn.xval.fc.base.exception.BusinessException;
import cn.xval.fc.core.security.TokenContext;
import cn.xval.ft.app.gen.database.entity.ProductContact;
import cn.xval.ft.app.gen.database.repository.ProductContactRepository;
import cn.xval.ft.app.gen.params.ProductContactParams;
import cn.xval.ft.app.gen.service.ProductContactService;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;

@Service
public class ProductContactImpl extends TokenContext implements ProductContactService {
    @Resource
    private ProductContactRepository repoProductContact;
    @Override
    public ProductContactParams.ProductContactInfo create(ProductContactParams.ProductContactCreateRequest arg) throws BusinessException {
        var entity = new ProductContact();
        entity.setCode(arg.getCode());
        entity.setName(arg.getName());
        entity.setExpire(arg.getExpire());
        this.repoProductContact.save(entity);
        return translate2Info(entity);
    }
    @Override
    public void remove(String id) throws BusinessException {
        this.repoProductContact.deleteById(decryptLong(id));
    }
    @Override
    public ProductContactParams.ProductContactInfo modify(ProductContactParams.ProductContactModifyRequest arg) throws BusinessException {
        var entityId = decryptLong(arg.getId());
        var entityOpt = this.repoProductContact.findById(entityId);
        Asserts.Business.withStatusText("记录不存在").assertTrue(entityOpt.isPresent(), "记录不存在: %s", entityId);
        var entity = entityOpt.get();
        entity.setCode(arg.getCode());
        entity.setName(arg.getName());
        this.repoProductContact.save(entity);
        return translate2Info(entity);
    }
    @Override
    public List<ProductContactParams.ProductContactInfo> list() throws BusinessException {
        var list = this.repoProductContact.findAll();
        var results = new ArrayList<ProductContactParams.ProductContactInfo>();
        for (var ent: list) {
            results.add(translate2Info(ent));
        }
        return results;
    }
    public ProductContactParams.ProductContactInfo translate2Info(ProductContact arg) throws BusinessException {
        var info = new ProductContactParams.ProductContactInfo();
        info.setId(encrypt(arg.getId()));
        info.setCode(arg.getCode());
        info.setName(arg.getName());
        info.setCreateTime(arg.getCreateTime());
        info.setUpdateTime(arg.getUpdateTime());
        info.setExpire(arg.getExpire());
        return info;
    }
}

